package com.sleep.satokendemo.controller;

import com.sleep.satokendemo.dto.SseDto;
import com.sleep.satokendemo.dto.TimeDemoDto;
import com.sleep.satokendemo.entry.R;
import com.sleep.satokendemo.server.DubboTestService;
import com.sleep.satokendemo.util.SseEmitterUtil;
import com.sleep.satokendemo.vo.SseResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.*;

/**
 * @author GuoAo
 * @className TestController
 * @date 2024/12/16
 * @description TODO
 */
@RestController
@Slf4j
@RequestMapping("/test")
public class TestController {

    @Autowired
    private DubboTestService dubboTestService;

    @PostMapping("/timeDemo")
    public R testTime(@RequestBody @Validated TimeDemoDto timeDemoDto){
        log.info("前端输入数据：{}",timeDemoDto);
        return R.success("success",timeDemoDto);
    }

    @GetMapping("/sse/connect/{id}")
    public SseEmitter connect(@PathVariable Integer id){
        return SseEmitterUtil.connect(id);
    }

    /**
     *  基于这个请求发送后续的消息
     * @param sseDto
     * @return
     */
    @PostMapping("/sse/sendMessage")
    public R sendMessage(@RequestBody SseDto sseDto){
        java.util.concurrent.ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(10, r -> {
            Thread thread = new Thread(r);
            thread.setName("scheduledExecutorService"+thread.getId());
            return thread;
        }, new ThreadPoolExecutor.CallerRunsPolicy()) {
        };
        for(int i = 0; i < 10; i++){
            service.schedule(()->{
                SseEmitterUtil.sendMessage(sseDto.getUserId(), sseDto.getMessage());
            },i * 1000,TimeUnit.MILLISECONDS);
        }
        SseResult sseResult = new SseResult();
        return R.success("success", sseResult);
    }

    @PostMapping("/sse/sendStreamMessage")
    public R sendStreamMessage(@RequestParam Integer userId, @RequestParam String message){
        SseEmitterUtil.sendStreamMessage(userId,message);
        return R.success("success");
    }

    /**
     * 模拟文本流 持续向前端返回文本
     * @param response
     * @throws IOException
     */
    @GetMapping("/textStream")
    public void textStream(HttpServletResponse response) throws IOException {
        response.setContentType("text/stream");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        for (int i = 0; i < 10; i++){
            try {
                Thread.sleep(1000);
                writer.write(String.format("data:textDemo date:%s \n", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())));
                writer.flush();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        writer.close();
    }

    @GetMapping("/dubbo")
    public R dubbo(){
        dubboTestService.test();
        return R.success("success");
    }

}
